package com.gym.Reflection;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.Properties;


/**
 * 反射测试
 * @author admin
 *
 */
public class ReflectionTest {
	
	public static void main(String[] args) throws ClassNotFoundException, UnsupportedEncodingException, IOException {
		String name = "com.gym.Thread.bank.Account";
		try {
			//通过类名加载实列
			Class class1 = Class.forName(name);
			//通过类的Class对象，产生实列的实际对象，调用Account的默认空构造方法
			Object object = class1.newInstance();
			//通过Class实例对象获取属性值，只能获取共有属性
			Field field = class1.getField("name");
			//通过属性对象给属性赋值
			field.set(object, "1212");
			//获取属性的值
			Object obj2 = field.get(object);
			System.err.println(field.get(object));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//1.获取一个系统类加载器
		ClassLoader classLoader = ClassLoader.getSystemClassLoader();
		System.err.println(classLoader);
		//2.获取系统类加载器的父类加载器，即扩展类加载器
		classLoader = classLoader.getParent();
		System.err.println(classLoader);
		//3.获取扩展类加载器的父类加载器，即引导类加载器,C++写的，拿不到
		classLoader = classLoader.getParent();
		System.err.println(classLoader);
		//4.测试当前类由哪个类加载器进行加载
		classLoader = Class.forName(name).getClassLoader();
		System.out.println(classLoader);
		//5.测试JDK提供的Object类由哪个类加载器加载(由引导加载器加载)
		classLoader = Class.forName("java.lang.Object").getClassLoader();
		System.out.println(classLoader);
		//*6.关于类加载器的一个主要方法：getResourceAsStream(String str):获取类路径下的指定文件的输入流：此路径是指绝对路径，src下
		InputStream in =ReflectionTest.class.getClassLoader().getResourceAsStream("com/gym/demo/text.properties");
		Properties properties = new Properties();
		properties.load(new InputStreamReader(in, "UTF-8"));
		String username = properties.getProperty("username");
		System.err.println(username);
	}

}
